<script setup>
import PageContainer from '@/components/PageContainer.vue'
import ChannelEdit from '@/views/article/components/ChannelEdit.vue'

import { ref } from 'vue'
import { articleDeleteChannelService, articleGetChannelService } from '@/api/article.js'

import { Delete, Edit } from '@element-plus/icons-vue'

const channelList = ref([])
const loading = ref(false)
const dialog = ref()

const getChannelList = async () => {
  loading.value = true
  const res = await articleGetChannelService()
  channelList.value = res.data.data
  loading.value = false
}

getChannelList()

const onEditChannel = (row) => {
  dialog.value.open(row)
}

const onDeleteChannel = async (row) => {
  try {
    await ElMessageBox.confirm('你确定要删除吗？', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })
    await articleDeleteChannelService(row.id)
    ElMessage.success('删除成功')
    await getChannelList()
  } catch (error) {
    // 用户取消删除或接口调用失败
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const addChannel = () => {
  dialog.value.open({})
}

const onSuccess = () => {
  getChannelList()
}
</script>

<template>
  <page-container title="文章分类">
    <template #extra>
      <el-button @click="addChannel">添加分类</el-button>
    </template>
    <el-table v-loading="loading" :data="channelList" style="width: 100%">
      <el-table-column type="index" label="序号" width="100"></el-table-column>
      <el-table-column prop="cate_name" label="分类名称"></el-table-column>
      <el-table-column prop="cate_alias" label="分类别名"></el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="{ row, $index }">
          <el-button
            :icon="Edit"
            circle
            type="primary"
            plain
            @click="onEditChannel(row, $index)"
          ></el-button>
          <el-button
            :icon="Delete"
            circle
            type="danger"
            plain
            @click="onDeleteChannel(row)"
          ></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据"></el-empty>
      </template>
    </el-table>
    <channel-edit ref="dialog" @success="onSuccess"></channel-edit>
  </page-container>
</template>

<style lang="scss" scoped></style>
